<template>
	<view class="content">
		<view class="item" v-for="(item, index) in data" :key="index">
			<view class="name">
				<text>{{ item.taskName }}</text>
				<text class="green">({{$t('inspection.offline.offline')}})</text>
			</view>
			<view class="desc">
				<view class="status" :class="{'blue':item.status === 0,'green':item.status === 1,'red':item.status === 2}">
					{{ item.status === 0 ? $t('inspection.offline.uploading') : item.status === 1 ? $t('inspection.offline.uploadSuccess') : $t('inspection.offline.uploadFail') }}
				</view>
				<view class="icon" v-if="showStatus">
					<uni-icons v-if="item.status === 0" type="spinner-cycle" color="#007aff"></uni-icons>
					<uni-icons v-if="item.status === 1" type="checkmarkempty" color="#3db213" size="20"></uni-icons>
					<uni-icons v-if="item.status === 2" type="closeempty" color="#f85556" size="20"></uni-icons>
				</view>
				<view class="btn">
					<button v-if="item.status === 2" type="primary" size="mini" @click="reupload(item)">{{$t('inspection.offline.reUpload')}}</button>
				</view>
			</view>
			<view class="red" v-if="item.status === 2">
				<text>{{ item.msg }}</text>
			</view>
		</view>
		<view class="func-btn">
			<button type="primary" size="mini" @click="closePop">{{$t('baseCommon.buttons.close')}}</button>
		</view>
	</view>
</template>

<script>
	import * as sqliteUtil from '@/utils/sqlite.js'
	import * as sqliteInspect from '@/utils/business/inspectSqlite.js'
	import { utilities, file } from '@/utils/common.js'
	import { uploadTask, logCollectStatusBatch } from '@/api/business/inspect.js'
	import { uploadDefect } from '@/api/business/defect.js'
	
	export default {
		props: {
			data: {
				type: Array,
				default () {
					return []
				}
			}
		},
		data() {
			return {
				showStatus: true
			}
		},
		created() {
			this.init()
		},
		methods: {
			init() {
				this.data.forEach(item=>{
					item.status = 0
					
					setTimeout(()=>{
						this.uploadTask('first', item)
					}, 500)
				})
			},
			async uploadTask(uploadType, item) {
				item.status = 0
				this.showStatus = false
				
				// 巡检任务
				let taskList = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', item.taskId)
				utilities.formatHumpLineTransfer(taskList)
				// 巡检任务附件
				let taskFiles = await this.getFileList(taskList)
				
				// 检查项
				let inspectList = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', item.taskId)
				utilities.formatHumpLineTransfer(inspectList)
				// 检查项附件
				let inspectFiles = await this.getFileList(inspectList)
				
				// 检查项测点
				let inspMpList = await sqliteUtil.selectTableInfo('m_ri_task_insp_mp', 'task_id', item.taskId)
				utilities.formatHumpLineTransfer(inspMpList)
				
				// 异常情况
				let abnormalList = await sqliteUtil.selectTableInfo('m_ri_task_inspection_abnormal', 'task_id', item.taskId)
				utilities.formatHumpLineTransfer(abnormalList)
				
				// 缺陷
				let defectList = []
				for(let i=0; i<abnormalList.length; i++) {
					let item = abnormalList[i]
					if(item.dfNo) {
						await sqliteUtil.selectTableInfo('m_df_information', 'df_id', item.dfNo).then(res=>{
							utilities.formatHumpLineTransfer(res)
							defectList.push(res[0])
						})
					}
				}
				// 关联的缺陷附件
				let defectFiles = await this.getFileList(defectList)
				
				// 测量数据
				let mpDataList = []
				for(let i=0; i<inspMpList.length; i++) {
					let item = inspMpList[i]
					await sqliteInspect.getMpDataList(item.mpNo, taskList[0].actualStartTime, utilities.getNowDateTime()).then(res=>{
						if(res.length > 0) {
							utilities.formatHumpLineTransfer(res)
							// 长度超过300进行截取，防止接口报错
							res.forEach(item => {
								if(item.dataValue) {
									if(mpDataList.findIndex(r => r.mpDataId == item.mpDataId) === -1) {
										// let dataValueArr = item.dataValue.split(",")
										// if(dataValueArr.length > 300) {
										// 	dataValueArr = dataValueArr.slice(dataValueArr.length - 257)
										// 	item.dataValue = dataValueArr.join()
										// }
										mpDataList.push(item)
									}
								} else {
									sqliteUtil.deleteTableInfo('m_eq_mp_data', 'mp_data_id', item.mpDataId)
								}
							})
						}
					})
				}
				
				// 缺陷处理
				let defectFlag = await this.handleUpload('defect', defectFiles, defectList)
				
				// 检查项处理
				let inspectFlag = await this.handleUpload('inspect', inspectFiles, inspectList)
				
				// 巡检任务处理
				let taskFlag = await this.handleUpload('task', taskFiles, taskList)
				
				if(!defectFlag || !inspectFlag || !taskFlag) {
					item.status = 2
					this.showStatus = true
					return
				}
				
				// 调用上传接口（重新获取数据）
				// 巡检任务
				let newTaskList = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', item.taskId)
				utilities.formatHumpLineTransfer(newTaskList)
				
				// 检查项
				let newInspectList = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', item.taskId)
				utilities.formatHumpLineTransfer(newInspectList)
				
				// 补充信息
				let addList = await sqliteUtil.selectTableInfo('m_ri_task_info', 'task_id', item.taskId)
				utilities.formatHumpLineTransfer(addList)
				let addInfo = addList.length > 0 ? addList[0] : {}
				
				let taskInfo = newTaskList[0]
				taskInfo.taskInspectionList = newInspectList
				taskInfo.riTaskInspMpList = inspMpList
				taskInfo.riTaskInspAbnList = abnormalList
				
				let params = {
					riTaskIo: taskInfo,
					eqMpDataIoList: mpDataList,
					riTaskInfoIo: addInfo
				}
				
				await uploadTask(params).then(res=>{
					if(res.data) {
						item.status = 1
					} else {
						item.status = 2
						item.msg = res.msg
					}
				})
				
				// 业务操作日志
				this.$saveOpLog('offline_upload', 'offline_task', item.taskId)
				
				this.showStatus = true
				
				await sqliteInspect.createMRiTaskUpload()
				if(uploadType == 'first') { // 新增任务上传记录
					let params = {
						taskId: item.taskId,
						nodeId: 'inspect',
						nodeName: '巡检',
						seq: "",
						uploadState: item.status === 0 ? '0' : item.status === 1 ? '10' : '20',
						uploadTime: utilities.getNowDateTime(),
						createTime: utilities.getNowDateTime(),
						updateTime: utilities.getNowDateTime()
					}
					sqliteInspect.insertMRiTaskUpload(params)
				} else if(uploadType == 'again') { // 更新任务上传记录
					let data = [
						{
							key: "upload_state",
							value: item.status === 0 ? '0' : item.status === 1 ? '10' : '20'
						},
						{
							key: "update_time",
							value: utilities.getNowDateTime()
						}
					]
					let condition = [
						{
							key: "task_id",
							value: item.taskId
						}
					]
					sqliteUtil.modifyTableInfo('m_ri_task_upload', data, condition)
				}
				
				// 采集情况
				let collectList = await sqliteUtil.selectTableInfo('m_cpis_app_collect_status')
				utilities.formatHumpLineTransfer(collectList)
				logCollectStatusBatch(collectList)
				
				// 上传成功并且状态为已完成删除本地数据
				if(item.status === 1 && taskInfo.taskState == '3') {
					this.$emit("deleteTask", item.taskId)
				}
			},
			// 获取附件
			async getFileList(dataList) {
				let fileList = []
				for(let i=0; i<dataList.length; i++) {
					let item = dataList[i]
					let condition = [
						{ key: "attachment_id", value: item.attachFile },
						{ key: "upload_state", value: "0" }
					]
					let res = await sqliteUtil.selectTableInfoMore('m_cpis_file_attachment', condition)
					fileList = fileList.concat(res)
				}
				return fileList
			},
			// 上传处理
			async handleUpload(type, fileList, dataList) {
				try{
					for(let i=0; i<fileList.length; i++) {
						let item = fileList[i]
						utilities.formatHumpLineTransfer(item)
						if(item.attachmentId && item.attachmentId != 'null') {
							let formData = {
								collectionId: item.attachmentId,
								businessCode: type == 'defect' ? 'oh' : 'insp',
								subBusinessCode: type == 'defect' ? 'df' : 'task',
								businessDataCode: type == 'defect' ? this.$t('defect.common.def') : type == 'task' ? this.$t('inspection.taskPlan.finishReport') : this.$t('inspection.taskPlan.taskPlan'),
								fileSum: 1,
								userName: uni.getStorageSync("userName"),
								fileUserName: uni.getStorageSync("userName")
							}
							file.uploadFileset(item.filePath, formData).then(res => {
								// 更新附件表
								let info = [
									{
										key: "upload_state",
										value: "10"
									}
								]
								let condi = [
									{
										key: "id",
										value: item.id
									}
								]
								sqliteUtil.modifyTableInfo('m_cpis_file_attachment', info, condi)
							})
						}
					}
					
					// 上传缺陷
					if(type == 'defect') {
						for(let i=0; i<dataList.length; i++) {
							let item = dataList[i]
							
							let info = await sqliteUtil.selectTableInfo('m_df_information', 'df_id', item.dfId)
							if(info) {
								utilities.formatHumpLineTransfer(info)
								uploadDefect(info[0])
							}
						}
					}
				}catch(e){
					return false
				}
				return true
			},
			reupload(item) {
				this.uploadTask('again', item)
			},
			closePop() {
				this.$emit("close")
			}
		}
	}
</script>

<style lang="scss">
	.content {
		width: 350px;
		min-height: 150px;
		overflow-y: auto;
		background-color: #fff;
	}
	
	.item {
		margin: 10px 15px;
		border-bottom: 1px solid #eee;
	}
	
	.name {
		font-size: 16px;
	}
	
	.desc {
		display: flex;
		align-items: center;
		margin-top: 5px;
		
		view {
			flex: 1;
		}
	}
	
	.blue {
		color: #007aff;
	}
	
	.green {
		color: #3db213;
	}
	
	.red {
		color: #f85556;
	}
	
	.func-btn {
		margin-top: 50px;
		text-align: center;
	}
</style>
